import express from 'express';
import { createServer as createHttpServer } from 'http';
import { createServer as createHttpsServer } from 'https';
import fs from 'fs';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';

// 导入自定义模块
import { config, updateAnnouncedIp } from './config.js';
import { MediaManager } from './mediaManager.js';
import { StreamManager } from './streamManager.js';
import { SignalingServer } from './signaling.js';

// ES模块中获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

class MediasoupRTSPServer {
  constructor() {
    this.app = express();
    this.httpServer = null;
    this.httpsServer = null;
    this.mediaManager = null;
    this.streamManager = null;
    this.signalingServer = null;
    this.rtspHandler = null; // 确保存在此属性以避免引用错误
  }

  async initialize() {
    try {
      console.log('🚀 Starting Mediasoup RTSP Server...');
      
      // 更新配置中的 IP 地址
      updateAnnouncedIp();
      
      // 初始化 Express 应用
      this.setupExpress();
      
      // 创建 HTTP/HTTPS 服务器
      this.createServers();
      
      // 初始化 MediaManager
      await this.initializeMediaManager();

      // 初始化 Stream Manager
      this.initializeStreamManager();

      // 初始化信令服务器
      this.initializeSignalingServer();
      
      // 启动服务器
      this.startServers();
      
      console.log('✅ Mediasoup RTSP Server started successfully!');
      
    } catch (error) {
      console.error('❌ Failed to start server:', error);
      process.exit(1);
    }
  }

  setupExpress() {
    console.log('Setting up Express application...');
    
    // 中间件
    this.app.use(cors());
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));
    
    // 静态文件服务 (为前端提供服务)
    const publicPath = path.join(__dirname, '../public');
    this.app.use(express.static(publicPath));

    // 提供 mediasoup-client 库
    const mediasoupClientPath = path.join(__dirname, '../node_modules/mediasoup-client/lib');
    this.app.use('/mediasoup-client', express.static(mediasoupClientPath));
    
    // API 路由
    this.setupRoutes();
  }

  setupRoutes() {
    // 健康检查
    this.app.get('/api/health', (req, res) => {
      res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        mediasoup: {
          worker: this.mediaManager?.getWorker()?.pid || null,
          router: this.mediaManager?.getRouter()?.id || null
        },
        rtsp: {
          active: this.rtspHandler?.isStreamActive() || false
        }
      });
    });

    // 获取 Router RTP Capabilities
    this.app.get('/api/rtp-capabilities', (req, res) => {
      try {
        const rtpCapabilities = this.mediaManager.getRouterRtpCapabilities();
        res.json({ rtpCapabilities });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 启动 RTSP 流
    this.app.post('/api/rtsp/start', async (req, res) => {
      try {
        const { rtspUrl } = req.body;
        
        if (!rtspUrl) {
          return res.status(400).json({ error: 'RTSP URL is required' });
        }

        const result = await this.rtspHandler.startStream(rtspUrl);
        res.json(result);
        
      } catch (error) {
        console.error('Error starting RTSP stream:', error);
        res.status(500).json({ error: error.message });
      }
    });

    // 停止 RTSP 流
    this.app.post('/api/rtsp/stop', async (req, res) => {
      try {
        await this.rtspHandler.stopStream();
        res.json({ success: true, message: 'RTSP stream stopped' });
        
      } catch (error) {
        console.error('Error stopping RTSP stream:', error);
        res.status(500).json({ error: error.message });
      }
    });

    // 获取 RTSP 流状态
    this.app.get('/api/rtsp/status', (req, res) => {
      try {
        const producers = this.rtspHandler.getProducers();
        res.json({
          active: this.rtspHandler.isStreamActive(),
          producers: {
            video: producers.video?.id || null,
            audio: producers.audio?.id || null
          }
        });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 获取统计信息
    this.app.get('/api/stats', async (req, res) => {
      try {
        const stats = await this.mediaManager.getStats();
        res.json(stats);
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 默认路由 - 返回前端应用
    this.app.get('/', (req, res) => {
      res.sendFile(path.join(__dirname, '../index.html'));
    });
  }

  createServers() {
    console.log('Creating servers...');
    
    // 读取SSL证书配置
    const sslOptions = this.getSSLOptions();
    
    // 创建HTTPS服务器（主服务器）
    this.httpsServer = createHttpsServer(sslOptions, this.app);
    
    // 创建HTTP服务器（仅用于重定向到HTTPS）
    this.httpServer = createHttpServer((req, res) => {
      // 将HTTP请求重定向到HTTPS
      const host = req.headers.host?.replace(config.http.port, config.https.port) || `${config.host}:${config.https.port}`;
      res.writeHead(301, { Location: `https://${host}${req.url}` });
      res.end();
    });
  }

  getSSLOptions() {
    try {
      // 证书文件路径配置
      const privateKeyPath = path.join(__dirname, './ssl/three-webgl.xyz.key');
      const publicCertPath = path.join(__dirname, './ssl/three-webgl.xyz_public.crt');
      const chainCertPath = path.join(__dirname, './ssl/three-webgl.xyz_chain.crt');

      // 检查文件是否存在
      const checkFileExists = (filePath) => {
        if (!fs.existsSync(filePath)) {
          throw new Error(`证书文件不存在: ${filePath}`);
        }
      };
      checkFileExists(privateKeyPath);
      checkFileExists(publicCertPath);
      checkFileExists(chainCertPath);

      // 读取证书文件并配置
      return {
        key: fs.readFileSync(privateKeyPath),
        cert: fs.readFileSync(publicCertPath),
        ca: fs.readFileSync(chainCertPath),
        minVersion: 'TLSv1.2',
        ciphers: 'HIGH:!aNULL:!MD5:!3DES',
        honorCipherOrder: true
      };
    } catch (error) {
      console.error('❌ SSL证书配置失败:', error.message);
      throw error;
    }
  }

  async initializeMediaManager() {
    console.log('Initializing MediaManager...');
    this.mediaManager = new MediaManager(config);
    await this.mediaManager.initialize();
  }

  initializeStreamManager() {
    console.log('Initializing Stream Manager...');
    this.streamManager = new StreamManager(
      this.mediaManager.getRouter(),
      config
    );

    // 监听流管理器事件
    this.streamManager.on('streamStarted', (data) => {
      console.log('Stream started:', data);
    });

    this.streamManager.on('streamStopped', (data) => {
      console.log('Stream stopped:', data);
    });
  }

  initializeSignalingServer() {
    console.log('Initializing Signaling Server...');
    this.signalingServer = new SignalingServer(
      this.httpsServer,
      this.mediaManager,
      this.streamManager,
      config
    );
  }

  startServers() {
    const { port: httpPort, host } = config.http;
    const { port: httpsPort } = config.https;
    
    // 启动HTTPS服务器（主服务器）
    this.httpsServer.listen(httpsPort, host, () => {
      console.log(`🌐 HTTPS Server running on https://${host}:${httpsPort}`);
      console.log(`📡 WebSocket server ready for secure connections`);
    });
    
    // 启动HTTP服务器（仅用于重定向）
    this.httpServer.listen(httpPort, host, () => {
      console.log(`🔄 HTTP Server running on http://${host}:${httpPort} (redirecting to HTTPS)`);
    });
    
    console.log(`🎥 RTSP streaming server ready`);
    console.log('');
    console.log('Available endpoints:');
    console.log(`  - Health check: https://${host}:${httpsPort}/api/health`);
    console.log(`  - RTP Capabilities: https://${host}:${httpsPort}/api/rtp-capabilities`);
    console.log(`  - Start RTSP: POST https://${host}:${httpsPort}/api/rtsp/start`);
    console.log(`  - Stop RTSP: POST https://${host}:${httpsPort}/api/rtsp/stop`);
    console.log(`  - RTSP Status: https://${host}:${httpsPort}/api/rtsp/status`);
    console.log(`  - Stats: https://${host}:${httpsPort}/api/stats`);
  }

  setupGracefulShutdown() {
    const shutdown = async (signal) => {
      console.log(`\n🛑 Received ${signal}, shutting down gracefully...`);
      
      try {
        // 停止 RTSP 流
        if (this.rtspHandler) {
          await this.rtspHandler.stopStream();
        }
        
        // 清理 MediaManager
        if (this.mediaManager) {
          await this.mediaManager.cleanup();
        }
        
        // 关闭服务器
        if (this.httpsServer) {
          this.httpsServer.close();
        }
        
        if (this.httpServer) {
          this.httpServer.close(() => {
            console.log('✅ Server shutdown completed');
            process.exit(0);
          });
        }
        
      } catch (error) {
        console.error('❌ Error during shutdown:', error);
        process.exit(1);
      }
    };

    process.on('SIGINT', () => shutdown('SIGINT'));
    process.on('SIGTERM', () => shutdown('SIGTERM'));
  }
}

// 启动服务器
const server = new MediasoupRTSPServer();
server.initialize().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});
    